package com.hmall.trade.listener;

import com.hmall.trade.constants.MQConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author: zhengsuyang
 * @Desc:
 * @create: 2025-11-06 17:14
 **/
@Component
@RequiredArgsConstructor
public class PayUpdateStatus {
    private final IOrderService orderService;
    @RabbitListener(bindings = @QueueBinding
            (value = @Queue(name = "trade.pay.success.queue", durable = "true"),
            exchange = @Exchange(name = "pay.topic",type = ExchangeTypes.TOPIC),
            key = "pay.success"))
    public void updateStatus(Long orderId){
        orderService.markOrderPaySuccess(orderId);
        System.out.println("通过MQ实现订单支付成功，更新订单状态");
    }

    /**
     * 延时消息取消订单
     * @param orderId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.DELAY_ORDER_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(name = MQConstants.DELAY_EXCHANGE_NAME,delayed = "true",type = ExchangeTypes.DIRECT),
            key = MQConstants.DELAY_ORDER_KEY
    ))
    public void cancelOrder(Long orderId){
        // 先根据id查询订单是否存在
        Order order = orderService.getById(orderId);
        if (order == null){
            System.out.println("订单不存在");
            return;
        }
        if (order.getStatus() == 1){
            orderService.cancelOrder(orderId);
        }
        System.out.println("通过MQ实现延时消息取消订单");
    }

}
